package com.zxy.supplier_system.server.repository

import com.zxy.supplier_system.server.controller.GoodsCategoryController
import com.zxy.supplier_system.server.entity.*
import com.zxy.supplier_system.server.utils.SpecificationUtils
import org.springframework.data.jpa.domain.Specification
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor

interface GoodsCategoryRepository :JpaRepository<GoodsCategory,Int>,JpaSpecificationExecutor<GoodsCategory>{

    fun findAllBySystemService(systemService: SystemService):List<GoodsCategory>
    fun findByIdAndSystemService(it: Int, currentSystemService: SystemService):GoodsCategory?

    fun findFirstByNameAndSystemService(name: String, systemService: SystemService): GoodsCategory?

    object Specifications{

        fun fromQueryGoodsCategories(queryGoodsCategoriesRequest: GoodsCategoryController.QueryGoodsCategoriesRequest):Specification<GoodsCategory>{
            return Specification.allOf(Specifications.nameContains(queryGoodsCategoriesRequest.name))
        }

        fun nameContains(name:String?):Specification<GoodsCategory>{
            return SpecificationUtils.contains({
                it.get("name")
            },name)
        }

        fun inMarketGoods(marketId: Int): Specification<GoodsCategory> {
            return Specification { root, query, criteriaBuilder ->
                val `in` = criteriaBuilder.`in`(root.get<Int>("id"))
                val subQuery = query.subquery(Int::class.java)
                val marketGoodsRoot = subQuery.from(MarketGoods::class.java)
                subQuery.select(
                    marketGoodsRoot.join<MarketGoods, Goods>("goods").join<Goods, GoodsCategory>("category").get("id")
                ).distinct(true)
                subQuery.where(
                    criteriaBuilder.equal(
                        marketGoodsRoot.join<MarketGoods, Market>("market").get<Int>("id"),
                        marketId
                    )
                )
                `in`.value(subQuery)
            }
        }

    }

}
